package com.sharelords.biz.creator.memory;

import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.ListBuffer;

import java.io.File;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;

/**
 * @author 千古龙少
 * @Description: java文件管理器，主要用来重新定义classLoader
 * @date 2020年6月14日 下午8:35:26
 */
class SpringJavaFileManager extends JavacFileManager {

    SpringJavaFileManager(Context context, boolean b, Charset charset) {
        super(context, b, charset);
    }

    @Override
    public ClassLoader getClassLoader(Location location) {
        nullCheck(location);
        Iterable iterable = this.getLocation(location);
        if (iterable == null) {
            return null;
        }

        ListBuffer<URL> buffer = new ListBuffer<>();
        for (Object o : iterable) {
            File file = (File) o;

            try {
                buffer.append(file.toURI().toURL());
            } catch (MalformedURLException var7) {
                throw new AssertionError(var7);
            }
        }

        return this.getClassLoader(buffer.toArray(new URL[0]));
    }

    @Override
    protected ClassLoader getClassLoader(URL[] urls) {
        ClassLoader classLoader = this.getClass().getClassLoader();
        try {
            Class<?> loaderClass = Class.forName("org.springframework.boot.loader.LaunchedURLClassLoader");
            Class[] classes = new Class[]{URL[].class, ClassLoader.class};
            Constructor var5 = loaderClass.getConstructor(classes);
            return (ClassLoader) var5.newInstance(urls, classLoader);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new URLClassLoader(urls, classLoader);
    }


}